package cn.ivast.recyclerviewtest;

import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.TimeInterpolator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;

import java.util.ArrayList;
import java.util.List;

import cn.ivast.recyclerviewtest.adapter.TanTanAdapter;

public class ViewPagerActivity extends AppCompatActivity {

    private TanTanAdapter adapter;
    RecyclerView recyclerView;
    private List<String> datas = new ArrayList<>();
    private int intentTop;
    private int intentLeft;
    private int intentWidth;
    private int intentHeight;
    private ColorDrawable colorDrawable;
    private int index;
    private int mLeftDelta;
    private int mTopDelta;
    private float mWidthScale;
    private float mHeightScale;
    private ImageView currentImageView;
    private ConstraintLayout clBg;
    private int SCREEN_HEIGHT;
    private int SCREEN_WIDTH;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_pager);

        Bundle bundle = getIntent().getExtras();
        intentTop = bundle.getInt(MainActivity.TOP);
        intentLeft = bundle.getInt(MainActivity.LEFT);
        intentWidth = bundle.getInt(MainActivity.WIDTH);
        intentHeight = bundle.getInt(MainActivity.HEIGHT);
        index = bundle.getInt(MainActivity.INDEX);

        clBg = findViewById(R.id.cl_bg);
        colorDrawable = new ColorDrawable(Color.BLACK);
        //布局背景设置
        clBg.setBackgroundDrawable(colorDrawable);
        initRecyclerView();

        recyclerView.scrollToPosition(index);

        DisplayMetrics displayMetrice = getDisplayMetrice(this);
        //屏幕高度
        SCREEN_HEIGHT = displayMetrice.heightPixels;
        //屏幕的宽度
        SCREEN_WIDTH = displayMetrice.widthPixels;

        if (savedInstanceState == null) {
            ViewTreeObserver observer = recyclerView.getViewTreeObserver();
            observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    recyclerView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    //坐标的获取设置
                    int[] screenLocation = new int[2];
                    RecyclerView.ViewHolder viewHolder = recyclerView.findViewHolderForAdapterPosition(index);
                    currentImageView = (ImageView) viewHolder.itemView;
                    currentImageView.getLocationOnScreen(screenLocation);
                    mLeftDelta = intentLeft - screenLocation[0];
                    mTopDelta = intentTop - screenLocation[1];
                    mWidthScale = (float) intentWidth / currentImageView.getWidth();
                    mHeightScale = (float) intentHeight / currentImageView.getHeight();
                    //开启缩放动画
                    enterAnimation();
                }
            });
//            observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
//                @Override
//                public boolean onPreDraw() {
//                    recyclerView.getViewTreeObserver().removeOnPreDrawListener(this);
//                    //坐标的获取设置
//                    int[] screenLocation = new int[2];
//                    RecyclerView.ViewHolder viewHolder = recyclerView.findViewHolderForAdapterPosition(index);
//                    currentImageView = viewHolder.itemView.findViewById(R.id.imageView);
//                    currentImageView.getLocationOnScreen(screenLocation);
//                    mLeftDelta = intentLeft - screenLocation[0];
//                    mTopDelta = intentTop - screenLocation[1];
//                    mWidthScale = (float) intentWidth / currentImageView.getWidth();
//                    mHeightScale = (float) intentHeight / currentImageView.getHeight();
//                    //开启缩放动画
//                    enterAnimation();
//                    return true;
//                }
//            });
        }
    }
    private static final int DURATION = 300;
    //进入动画
    public void enterAnimation() {
        if (currentImageView != null) {
            //设置imageview动画的初始值
            currentImageView.setPivotX(0);
            currentImageView.setPivotY(0);
            //设置缩放比例
            currentImageView.setScaleX(mWidthScale);
            currentImageView.setScaleY(mHeightScale);
            //设置移动距离
            currentImageView.setTranslationX(mLeftDelta);
            currentImageView.setTranslationY(mTopDelta);
            //设置动画
            TimeInterpolator sDecelerator = new DecelerateInterpolator();
            //设置imageview缩放动画，以及缩放开始位置
            currentImageView.animate().setDuration(DURATION).scaleX(1).scaleY(1).
                    translationX(0).translationY(0).setInterpolator(sDecelerator);

            clBg.setPivotX(0);
            clBg.setPivotY(0);
            clBg.setScaleX((float)(intentWidth/SCREEN_WIDTH));
            clBg.setScaleY((float)(intentHeight/SCREEN_HEIGHT));
            int[] screenLocation = new int[2];
            clBg.getLocationOnScreen(screenLocation);
            clBg.setTranslationX(intentLeft-screenLocation[0]);
            clBg.setTranslationY(intentTop-screenLocation[1]);
            clBg.animate().setDuration(DURATION).scaleX(1).scaleY(1).
                    translationX(0).translationY(0).setInterpolator(sDecelerator);

            // 设置activity主布局背景颜色DURATION毫秒内透明度从透明到不透明
            ObjectAnimator bgAnim = ObjectAnimator.ofFloat(clBg, "alpha", 0f, 1f);
            bgAnim.setDuration(DURATION);
            bgAnim.start();
            bgAnim.addListener(new AnimatorListenerAdapter() {
            });
        }
    }

    public void exitAnimation(final Runnable endAction) {

        TimeInterpolator sInterpolator = new AccelerateInterpolator();
        //设置imageview缩放动画，以及缩放结束位置
        currentImageView.animate().setDuration(DURATION).scaleX(mWidthScale).scaleY(mHeightScale).
                translationX(mLeftDelta).translationY(mTopDelta)
                .setInterpolator(sInterpolator).withEndAction(endAction);


        int[] screenLocation = new int[2];
        clBg.getLocationOnScreen(screenLocation);
        clBg.animate().setDuration(DURATION).scaleX((float)(intentWidth/SCREEN_WIDTH)).scaleY((float)(intentHeight/SCREEN_HEIGHT)).
                translationX(intentLeft-screenLocation[0]).translationY(intentTop-screenLocation[1])
                .setInterpolator(sInterpolator).withEndAction(endAction);

        // 设置activity主布局背景颜色DURATION毫秒内透明度从不透明到透明
        ObjectAnimator bgAnim = ObjectAnimator.ofFloat(clBg, "alpha", 1f,0f);
        bgAnim.setDuration(DURATION);
        bgAnim.start();
    }

    private DisplayMetrics getDisplayMetrice(Context context) {
        if (context == null) {
            return null;
        }
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        if (windowManager != null) {
            windowManager.getDefaultDisplay().getMetrics(dm);
        }
        return dm;
    }

    @Override
    public void onBackPressed() {
        exitAnimation(new Runnable() {
            @Override
            public void run() {
                finish();
                overridePendingTransition(0, 0);
            }
        });
    }

    private void initRecyclerView() {
        recyclerView = findViewById(R.id.recyclerView);

        datas.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1543140604386&di=1027e9678e0133cda11263591c31d14a&imgtype=0&src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2F54ebececeda0217648263cc944d6cfd413a17cdf2cc6-MGHS0y_fw658");
        datas.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1543206559235&di=c2a52beb6af677c9a802ff1b781922f7&imgtype=0&src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2Fd17ad2565b6418379b5e7a3393bab02514de0d8925ce-IDo8Q2_fw658");
        datas.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1543140605094&di=cf2c33d764278c094002326c6690ab2e&imgtype=0&src=http%3A%2F%2Fimgsrc.baidu.com%2Fimgad%2Fpic%2Fitem%2Fc8ea15ce36d3d539ecadcfee3187e950352ab00f.jpg");
        datas.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1543140605092&di=d833a4fdb650c85c82687c72434ea64f&imgtype=0&src=http%3A%2F%2Fimg006.hc360.cn%2Fhb%2FMTQ3NDYwMTg2NTk0MTEzMTkzMjAwMTU%3D.jpg");
        datas.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1543140605092&di=d90d56a3827d5fce315cdba0604eb37b&imgtype=0&src=http%3A%2F%2Fimg66.jc35.com%2F9%2F20160114%2F635883614235589122892.jpg");
        datas.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1543140605091&di=a7700cab6921e3c658d627736c72a230&imgtype=0&src=http%3A%2F%2Fh.hiphotos.baidu.com%2Fzhidao%2Fpic%2Fitem%2F0e2442a7d933c895feee1630d11373f0830200ec.jpg");
        datas.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1543140605088&di=f93329e7e03b0e9b05d2014f4179beca&imgtype=0&src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2F4215df5b2fd0e479834179dfeb8b3f0210c55488dd38-3H2Qvj_fw658");


        adapter = new TanTanAdapter(recyclerView);
        adapter.setData(datas);
        LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(adapter);
        ViewPagerSnapHelper snapHelper = new ViewPagerSnapHelper();
        snapHelper.attachToRecyclerView(recyclerView);
    }

    private class ViewPagerSnapHelper extends LinearSnapHelper {
        @Override
        public int findTargetSnapPosition(RecyclerView.LayoutManager layoutManager, int velocityX, int velocityY) {
            int targetPosition = super.findTargetSnapPosition(layoutManager, velocityX, velocityY);
            View currentView = findSnapView(layoutManager);
            if (targetPosition != RecyclerView.NO_POSITION && currentView != null) {
                int currPosition = layoutManager.getPosition(currentView);
                int first = ((LinearLayoutManager) layoutManager).findFirstVisibleItemPosition();
                int last = ((LinearLayoutManager) layoutManager).findLastVisibleItemPosition();
                currPosition = targetPosition < currPosition ? last : (targetPosition > currPosition ? first : currPosition);
                targetPosition = targetPosition < currPosition ? currPosition - 1 : (targetPosition > currPosition ? currPosition + 1 : currPosition);
            }
            return targetPosition;
        }
    }
}
